package com.weige.elefence.utils;

import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * 读取json文件，并将json转化为Map返回
 *
 * @author ltj
 */
public class ReadJsonFileUtil {
    private static final Logger log = LoggerFactory.getLogger(ReadJsonFileUtil.class);

    public static Map<String, String> map;

    public static void init() {
        // 根据相对路径获取当前项目下的配置文件
        String path = System.getProperty("user.dir") + "/cfg.json";
        log.info("cfg.json 路径 =" + path);
        map = ReadJsonFileUtil.getMap(path);


    }

    private static Map<String, String> getMap(String path) {
        String str = ReadJsonFileUtil.fileToString(path);
        JSONObject result = JSONObject.parseObject(str);
        log.info("cfg.json 内容 =" + result);
        Map<String, String> visitorDeviceMap = JSONObject.parseObject(result.getString("ele-fence"), Map.class);
        Map<String, String> mqMap = JSONObject.parseObject(result.getString(visitorDeviceMap.get("mq-mapping").toString()), Map.class);
        visitorDeviceMap.putAll(mqMap);
        return visitorDeviceMap;
    }

    /**
     * 将文件转换成String
     **/
    public static String fileToString(String pathStr) {
        String str = "";
        File file = new File(pathStr);
        try {
            FileInputStream in = new FileInputStream(file);
            // size 为字串的长度 ，这里一次性读完
            int size = in.available();
            byte[] buffer = new byte[size];
            in.read(buffer);
            in.close();
            str = new String(buffer, StandardCharsets.UTF_8);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return null;
        }
        return str;
    }
}
